<template>

    <div>
        <el-form :inline="true" :model="searchMap" style="margin: 20px" ref="searchFormRef">
            <el-form-item prop="teacher_id" style="width:200px">
                <el-select v-model="searchMap.teacher_id" placeholder="根据授课教师查询" clearable >
                
                    <el-option v-for="option in teacherOPtions" :label="option.name" :value="option._id"
                        :key="option._id" />
                    
                </el-select>
            </el-form-item>
            <el-form-item prop="manager_id" style="width:200px">
                <el-select v-model="searchMap.manager_id" placeholder="根据学管查询" clearable>
                    <el-option v-for="option in manageOptions" :label="option.name" :value="option._id"
                        :key="option._id" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="promary" @click="getClassList">查询</el-button>
                <el-button  @click="resetForm(searchFormRef)">重置</el-button>
                <el-button type="promary" @click="handleAdd">添加班级</el-button>
        </el-form-item>
        </el-form>
        <el-table :data="classes" heigh="300px" style="width: 100%;height: 500px;">

            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column label="班级名称" prop="classname"></el-table-column>
            <el-table-column label="授课教师" prop="teacher_id" :formatter="formatTeacher"></el-table-column>
            <el-table-column label="学管" prop="manager_id" :formatter="formatManage"></el-table-column>

            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row._id)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        <!-- 添加/编辑班级弹窗 -->

        <el-dialog v-model="classFormVisible" title=" 添加/编辑班级" width="500">
            <el-form :model="updateClass" :rules="rules" ref="calssFormRef" style="width:400px" label-width="100px"
                label-position="right">
                <el-form-item label="班级名称" prop="classname">
                    <el-input v-model="updateClass.classname" />
                </el-form-item>

                <el-form-item label="授课教师" prop="teacher_id">
                    <el-select v-model="updateClass.teacher_id" placeholder="请选择授课教师">
                        <el-option v-for="option in teacherOPtions" :label="option.name" :value="option._id"
                            :key="option._id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="学管" prop="manager_id">
                    <el-select v-model="updateClass.manager_id" placeholder="请选择学管">
                        <el-option v-for="option in manageOptions" :label="option.name" :value="option._id"
                            :key="option._id" />
                    </el-select>
                </el-form-item>



            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary"
                        @click="updateClass._id == null ? addData(calssFormRef) : updateData(calssFormRef)">
                        确定
                    </el-button>
                    <el-button @click="classFormVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { classInfoData } from '@/api/class/type';
import type { roleInforDate } from '@/api/role/type';
import type { userInfoData } from '@/api/user/type';
import useRoleStore from '@/store/modules/role';
import useUserStore from '@/store/modules/user';
import useClassStore from '@/store/modules/class';
import { nextTick, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
// 引入班级小仓库
/* 
现有内容：请求Api方法，数据类型，小仓库
1.显示数据列表 ——条件筛选
2.添加班级弹窗和功能
3.编辑弹窗回显以及更新数据
4.删除
*/
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  getClassList()
}
const searchFormRef = ref()


const classes = ref<classInfoData[]>([])
const classstore = useClassStore()
const roleStore = useRoleStore()
const userStore = useUserStore()
const classFormVisible = ref(false)
const updateClass = ref({
    _id: null,
    classname: '',
    teacher_id: '',
    manager_id: ''
})
const calssFormRef = ref()
const rules = reactive<FormRules>({
    classname: [{ required: true, message: "请输入班级名称", trigger: 'blur' }],
    teacher_id: [{ required: true, message: "请输入教师名称", trigger: 'blur' }],
    manager_id: [{ required: true, message: "请输入学管名称", trigger: 'blur' }]
})
const addData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            classstore.addClass(updateClass.value).then(() => {
                classFormVisible.value = false
                getClassList()
            })
        } else {
            console.log('error submit!')
        }
    })
}
const updateData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            classstore.upDataClass(updateClass.value).then(() => {
                classFormVisible.value = false
                getClassList()
            })

        } else {
            console.log('error submit!')
        }
    })
}
// 角色数组
const roleOptions = ref<roleInforDate[]>([]);
// 用户数组
const userOptions = ref<userInfoData[]>([]);
// 教师id
const teacher_role_id = ref('');
// 学管id
const manager_role_id = ref('');
// 教师数组
const teacherOPtions = ref<userInfoData[]>([]);
// 学管数组
const manageOptions = ref<userInfoData[]>([]);
// 获取角色数组
const getRoleList = () => {
    return new Promise((resolve, _reject) => {
        if (roleStore.roles && roleStore.roles.length) {
            roleOptions.value = roleStore.roles;
            roleOptions.value.forEach((item) => {
                if (item.name == "教师") {


                    teacher_role_id.value = item._id as string

                } else if (item.name == "学管") {
                    manager_role_id.value = item._id as string

                }

            });
            resolve(true)
        } else {

            roleStore.getRoleList().then(() => {
                // @ts-ignore
                roleOptions.value = roleStore.roles;
                roleOptions.value.forEach((item) => {
                    if (item.name == "教师") {
                        teacher_role_id.value = item._id as string
                    } else if (item.name == "学管") {
                        manager_role_id.value = item._id as string
                    }
                })
                resolve(true)
            })
        }
    })
}
// 获取用户数组
const getUserList = () => {

    return new Promise((resolve, _reject) => {

        if (userStore.users && userStore.users.length) {
            userOptions.value = userStore.users

            userOptions.value.forEach((item) => {
                if (item.role_id == teacher_role_id.value) {
                    teacherOPtions.value.push(item);
                } else if (item.role_id == manager_role_id.value) {
                    manageOptions.value.push(item)
                }
            })
            resolve(true)
        } else {
            userStore.getUserAll().then(() => {
                userOptions.value = userStore.users
                userOptions.value.forEach((item) => {

                    if (item.role_id == teacher_role_id.value) {
                        teacherOPtions.value.push(item);
                        console.log('userOptions.value', teacherOPtions.value);
                    } else if (item.role_id == manager_role_id.value) {
                        manageOptions.value.push(item)
                    }
                })
            })
            resolve(true)
        }
    })
}
// 格式化教师
const formatTeacher = (
    _row: any,
    _colum: any,
    cellValue: string,
    _index: number
) => {
    let teacher = teacherOPtions.value.find(
        (item) => item._id == cellValue
    );
    return teacher?.name
}
// 格式化学管
const formatManage = (
    _row: any,
    _colum: any,
    cellValue: string,
    _index: number
) => {
    let manager = manageOptions.value.find(
        (item) => item._id == cellValue
    );
    return manager?.name
}
const handleEdit = (_id: string) => {
    handleAdd();
    classstore.getClassById(_id).then((response) => {
        // @ts-ignore
        updateClass.value = response
    })
}
const handleDelete = (_id: string) => {
    ElMessageBox.confirm(
        '确定要删除此条数据吗？',
        'Warning', {
        // if you want to disable its autofocus
        // autofocus: false,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
    })
        .then(() => {
            classstore.deleteClass(_id).then(() => {

                ElMessage({
                    type: "success",
                    message: "删除成功",
                });
                getClassList()
            })
                .catch(() => { })
        })
}
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    getClassList()
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getClassList()
}
const searchMap = ref({
    teacher_id: '',
    manager_id: ''
})
const getClassList = () => {
    classstore.getClassList({ page: currentPage.value, size: pageSize.value, searchMap: searchMap.value }).then((response) => {
        classes.value = classstore.classes as classInfoData[]
        // @ts-ignore
        total.value = response?.total
    })
}
const handleAdd = () => {
    classFormVisible.value = true
    updateClass.value = {
        _id: null,
        classname: '',
        teacher_id: '',
        manager_id: ''
    }
    nextTick(() => {
        calssFormRef.value.resetFields()
    })
}
onMounted(() => {

    getRoleList().then(() => {
        getUserList().then(() => {
            getClassList()
        })
    })
})
</script>

<style scoped></style>